﻿layui.use(function () {
    page.init();//初始化页面


});

var page = {
    deskRow: 8,
    deskCol: 8,
    students: [],//学生列表
    seats: [],//包括座位号信息

    init: function () {

        //var students = page.getStudents();
        //var queryData = jsonsql.query("select * from json where (name !='张三4')", students);
        //console.log(students);
        //console.log(queryData);
        //queryData[0].height = 88;
        //console.log(students);
        //console.log(queryData);


        this.deskRow = 8;
        this.deskCol = 8;
        this.setSeatChart();//初化座位表
        this.initForm();
        this.initStudentContainer();
        this.initSeatChart();
    },
    //初始化所有表单事件
    initForm: function () {
        var $ = layui.jquery;
        // 提交事件
        layui.form.on('submit(seat-chart-setting)', function (data) {
            var field = data.field; // 获取表单字段值
            page.deskRow = field.deskRow;
            page.deskCol = field.deskCol;
            page.setSeatChart(); //渲染座位表  
            return false; // 阻止默认 form 跳转
        });
        //导入名单事件
        $("#importStudents").on("click", function () {
            //导入名单事件
            page.getStudents();//获得学生数据
            page.studentListRender(); //初始化学生容器
        });

        //下载名单模板
        $("#downloadTpl").on("click", function () {
            alert("下载学生模板");
        });


        $("#delSeatCol").on("click", function () {
            layer.prompt({
                value: page.deskCol,
                title: '请输入要删除的座位列？',
            }, function (value, index, elem) {
                if (!(/^[1-9]\d*$/.test(value))) {
                    layui.layer.msg("输入非法数字，导致删除失败！", {
                        icon: 2, time: 2000, //offset: "rt"
                    });
                }
                var col = parseInt(value);
                if (col > page.deskCol) {
                    layui.layer.msg("输入的课桌行大于现有座位表的行数，导致删除失败！", {
                        icon: 2, time: 2000, //offset: "rt"
                    });
                }
                //执行删除操作
                var $seatCol = $("#seatCol" + col);
                if ($seatCol.length == 0) {


                } else {
                    var $seatCards = $seatCol.find(".seat-card");
                    $.each($seatCards, function (index2, item) {
                        var $seat = $(item);
                        var $parent = $seat.closest(".seat");
                        if ($parent.hasClass("seat-assigned")) {
                            var oldStudent = {};
                            oldStudent.id = $seat.attr("data-id");
                            $("#student" + oldStudent.id).removeClass("student-hide");
                        }
                    });
                }
                $("#delSeatRow").on("click", function () {
                    layer.prompt({
                        value: page.deskCol,
                        title: '请输入要删除的座位行？',
                    }, function (value, index, elem) {

                        $seatCol.remove();
                        layer.close(index); // 关闭层
                    });
                });

            });
        });



        //行列对调事件
        layui.dropdown.render({
            elem: '#reloadTest', // 可绑定在任意元素中，此处以上述按钮为例
            data: [{
                id: 'reload',
                title: '行对调'
            }, {
                id: 'reload-deep',
                title: '列对调'
            }],
            // 菜单被点击的事件
            click: function (obj) {
                switch (obj.id) {
                    case 'reload':
                        break;
                }
            }
        });
    },
    //初始学生容器
    initStudentContainer: function () {
        var $ = layui.jquery;
        //初始化学生容器
        $("#studentContainer").empty();//清空学生列表
        //学生信息拖动开始事件
        $(document).on('dragstart', '.student-card', function (e) {
            var $draggedItem = $(this); //当前元素
            var $parent = $draggedItem.closest(".student");
            var student = {};
            student.id = $draggedItem.attr("data-id");         
            student.sourceType = "student";
            e.originalEvent.dataTransfer.effectAllowed = "move"; //设置成移动效果 copy 复制 link 链接
            e.originalEvent.dataTransfer.setData("text/plain", JSON.stringify(student));
            $draggedItem.addClass("dragging");
        });

        // 学生信息拖动结束事件
        $(document).on('dragend', '.student-card', function (e) {
            var $draggedItem = $(this);
            $draggedItem.removeClass("dragging");
        });

        // 使用事件委托为现有和将来的.drop-zone元素绑定dragover事件
        $(document).on('dragover', '.student-container', function (e) {
            e.preventDefault();
        });

        //当学生信息元素放置到放置位置元素区域时
        $(document).on('drop', '.student-container', function (e) {
            var text = e.originalEvent.dataTransfer.getData("text/plain");
            var student = JSON.parse(text);//解析学生信息
            if (student.sourceType == "seat") {
                e.preventDefault();
                page.revokeSeatToStudent(student.row, student.col); //撤销座位安排         
            }
        });
    },
    //初化座位表容器
    initSeatChart: function () {
        var $ = layui.jquery;
        var laytpl = layui.laytpl;

        //锁定座位
        $(document).on('click', '.seat-locked-state .layui-icon-lock', function (e) {
            var $seat = $(this).closest(".seat");
            var row = $seat.attr("data-row");
            var col = $seat.attr("data-col");
            page.lockingSeat(row, col); //锁定座位信息
            return false;
        });

        //解锁座位
        $(document).on('click', '.seat-locked-state .layui-icon-disabled', function (e) {
            var $seat = $(this).closest(".seat");
            var row = $seat.attr("data-row");
            var col = $seat.attr("data-col");
            page.unlockingSeat(row, col); //锁定座位信息
            return false;        
        });

        //座位号拖动开始事件
        $(document).on('dragstart', '.seat-card', function (e) {
            var $draggedItem = $(this);
            var $parent = $draggedItem.closest(".seat");            
            var row = $parent.attr("data-row");
            var col = $parent.attr("data-col");
            var seat = {};
            seat.row = row;
            seat.col = col;           
            seat.sourceType = "seat";
            e.originalEvent.dataTransfer.effectAllowed = "move"; //设置成移动效果 copy 复制 link 链接
            e.originalEvent.dataTransfer.setData("text/plain", JSON.stringify(seat));
            $draggedItem.addClass("dragging");
        });

        //座位号拖拽结束事件
        $(document).on('dragend', '.seat-card', function (e) {
            var $draggedItem = $(this);
            $draggedItem.removeClass("dragging");
        });

        // 使用事件委托为现有和将来的.drop-zone元素绑定dragover事件
        $(document).on('dragover', '.seat', function (e) {
            if (!$(this).hasClass("seat-locked")) {
                e.preventDefault();
            }         
        });

        //当学生信息元素放置到放置位置元素区域时
        $(document).on('drop', '.seat-card', function (e) {
            var $seat = $(this);
            var $parent = $seat.closest(".seat");
            if (!$parent.hasClass("seat-locked")) {
                e.preventDefault();
                var row = $parent.attr("data-row");
                var col = $parent.attr("data-col");
                var text = e.originalEvent.dataTransfer.getData("text/plain");
                var moveInfo = JSON.parse(text);//解析学生信息
                if (student.sourceType == "student") {
                    //从学生列表拖拽来的数据时，则把当前信息还原到学生列表
                    page.allocationSeatToStudent(moveInfo.studentId, row, col);
                    $("#STU_" + moveInfo.studentId).removeClass("dragging");; //隐患原来的元素
                } else {
                    //进行互换
                    page.changeSeatBetweenSeat(moveInfo.row, moveInfo.col,row, col);
                }
            }
        });
    },
    oneClineAllocationSeats: function () {
        //一键分配座位：按条件分配【例如身高、成绩等】
        //对已安排座位的学生，不进行调整；对已锁定的座位，不进行调整
    },
    randomAllocationSeats: function () {
        //随机分配座位:随机打乱学生列表，然后依次分配到座位表
    },
    zShapedSeatAllocation: function () {
        //对已安排的座位进行Z字型分配座位；对已销定的座位，不进行调整
        for (var row = 1; row <= page.deskRow; row++) {
            //寻找可以开始的位置
            var seats = jsonsql.query(`select * from json where (row == ${row}) order by col asc`, page.seats);
            var startCol = startCol = row % page.deskCol; 
            var student = null;
            for (var col = startCol; col <= page.deskCol; col++) { 
                var seat = seats[col - 1];
                if (seat.locked == false) {
                    startCol = col;
                    student = seat.student;//获得学生信息                   
                    break;
                }
            }       
            for (var col = startCol+1; col <= page.deskCol; col++) {
                var seat = seats[col - 1];
                if (seat.locked == true) continue; //锁定的座位不进行交换
                var newStudent = seat.student;//获得学生信息
                seat.setStudent(student);
                student = newStudent; //继续下一个                 
            }
            for (var col = 1; col <= startCol-1; col++) {
                var seat = seats[col - 1];
                if (seat.locked == true) continue; //锁定的座位不进行交换
                var newStudent = seat.student;//获得学生信息
                seat.setStudent(student);
                student = newStudent; //继续下一个                 
            }
            seats[col - 1].setStudent(student);
            $.each(seats, function (index, item) {

                page.resetSeat(item); //重置座位

            });
        }
    },
    allocationSeatToStudent: function (studentId, row, col) {
        //给学生分配座位:给定学生ID，分配到指定的行列：从学生列表到座位表
        var $ = layui.jquery;
        var laytpl = layui.laytpl;

        //获得待分配的学生信息   
        var tempStudents = jsonsql.query(`select * from json where (id == ${studentId})`, page.students);
        if (!tempStudents || tempStudents.length == 0) return false;
        var student = tempStudents[0]; //获得学生信息

        //获得坐位信息
        var tempSeats = jsonsql.query(`select * from json where (col == ${col} && row ==${row} )`, page.seats);
        if (!tempSeats || tempSeats.length == 0) return false;
        var seat = tempSeats[0];
        if (seat.locked) {
            var msg = `课桌号${col}-${row}已锁定，导致移动失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }

        //判断当前座位是否已分配学生，如果已分配，则把原来的学生信息还原到学生列表
        if (seat.allocationed) {
            tempStudents = jsonsql.query(`select * from json where (id == ${seat.student.id})`, page.students);
            if (tempStudents && tempStudents.length > 0) {
                var student2 = tempStudents[0]; //获得学生信息
                student2.clearSeat(); //清空学生座位信息 
                $("#STU_" + student2.id).removeClass("student-hide"); //显示学生信息
            }
        }

        //设置学生的座位信息
        $("#STU_" + studentId).addClass("student-hide"); //隐藏学生信息     
        seat.setStudent(student); //设置座位的学生信息
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        tplInst = laytpl(seatTpl);
        tplInst.render(seat, function (html) {
            $("SEAT_R_" + seat.row + "_C_" + seat.col).replaceWith(html);// 渲染并输出结果  
        });
    },
    changeSeatBetweenSeat: function (row1, col1, row2, col2) {
        //给已安排座位的学生更换座位：交换两个座位的学生【源座位（row1,col1）】->[目标座位（row2,col2）]
        //当源座位存在学生信息时，才能移动和交换
        var $ = layui.jquery;
        var laytpl = layui.laytpl;

        //源座位信息获得
        var tempSeats = jsonsql.query(`select * from json where (col == ${col1} && row ==${row1} ) order by row asc`, page.seats);
        if (!tempSeats || tempSeats.length == 0) return false;
        var seat1 = tempSeats[0];
        if (seat1.locked == true) {
            var msg = `课桌号${col1}-${row1}已锁定，导致移动失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }
        if (seat1.allocationed == false) {
            var msg = `课桌号${col1}-${row1}未分配学生，导致移动失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }

        //目标座位信息获得:当目标座位锁定时，不能进行交换
        var tempSeats = jsonsql.query(`select * from json where (col == ${col2} && row ==${row2} ) order by row asc`, page.seats);
        if (!tempSeats || tempSeats.length == 0) return false;
        var seat2 = tempSeats[0];
        if (seat1.locked == true) {
            var msg = `课桌号${col2}-${row2}已锁定，导致移动失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }
        page.changeSeats(seat1, seat2);
        return true;
    },
    //重置座位
    resetSeat: function (seat) {
        if (!seat) return;
        if (!(seat.student instanceof SeatInfo)) return;
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        tplInst = laytpl(seatTpl);
        tplInst.render(seat, function (html) {
            $("SEAT_R_" + seat.row + "_C_" + seat.col).replaceWith(html);// 渲染并输出结果  
        });
    },
    //交换两个座位的基本信息
    changeSeats: function (seat1, seat2) {
        //两个位置进行对换
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        if (!seat1 || !seat2) return;
        var student1 = seat1.student;
        var student2 = seat2.student;
        seat1.setStudent(student2);
        seat2.setStudent(student1);
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        tplInst = laytpl(seatTpl);
        tplInst.render(seat1, function (html) {
            $("SEAT_R_" + seat1.row + "_C_" + seat1.col).replaceWith(html);// 渲染并输出结果  
        });
        tplInst.render(seat2, function (html) {
            $("SEAT_R_" + seat2.row + "_C_" + seat2.col).replaceWith(html);// 渲染并输出结果  
        });
    },
    changeRowSeats: function (row1, row2) {
        //交换两行座位以及学生信息，如果有锁定的座位，不进行交换
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var tempSeats1 = jsonsql.query(`select * from json where (row ==${row1} ) order by col asc`, page.seats);
        if (!tempSeats1 || tempSeats1.length == 0) {
            var msg = `课桌${row1}排不存在，导致交换失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }
        var tempSeats2 = jsonsql.query(`select * from json where (row ==${row2} ) order by col asc`, page.seats);
        if (!tempSeats2 || tempSeats2.length == 0) {
            var msg = `课桌${row2}排不存在，导致交换失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }
        //交换两行座位
        for (var col = 1; col <= page.col; col++) {
            var tempSeats = jsonsql.query(`select * from json where (col == ${col} && row ==${row1} ) order by col asc`, tempSeats1);
            if (!tempSeats || tempSeats.length == 0) continue;
            var seat1 = tempSeats[0];
            if (seat1.locked == true) continue; //锁定的座位不进行交换

            tempSeats = jsonsql.query(`select * from json where (col == ${col} && row ==${row2} ) order by col asc`, tempSeats2);
            if (!tempSeats || tempSeats.length == 0) continue;
            var seat1 = tempSeats[0];
            if (seat1.locked == true) continue; //锁定的座位不进行交换

            page.changeSeats(seat1, seat2); //交换两个座位           
        }
        return true;
    },
    changeColSeats: function (col1, col2) {
        //交换两列座位以及学生信息，如果有锁定的座位，不进行交换
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var tempSeats1 = jsonsql.query(`select * from json where (col ==${col1} ) order by row asc`, page.seats);
        if (!tempSeats1 || tempSeats1.length == 0) {
            var msg = `课桌${col1}列不存在，导致交换失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }
        var tempSeats2 = jsonsql.query(`select * from json where (col ==${col2} ) order by row asc`, page.seats);
        if (!tempSeats2 || tempSeats2.length == 0) {
            var msg = `课桌${col2}列不存在，导致交换失败！`;
            layui.layer.msg(msg, {
                icon: 2, time: 2000, //offset: "rt"
            });
            return false;
        }
        //交换两行座位
        for (var row = 1; row <= page.row; row++) {
            var tempSeats = jsonsql.query(`select * from json where (row == ${row} && col ==${col1} ) order by row asc`, tempSeats1);
            if (!tempSeats || tempSeats.length == 0) continue;
            var seat1 = tempSeats[0];
            if (seat1.locked == true) continue;

            tempSeats = jsonsql.query(`select * from json where (row == ${row} && col ==${col2} ) order by row asc`, tempSeats2);
            if (!tempSeats || tempSeats.length == 0) continue;
            var seat1 = tempSeats[0];
            if (seat1.locked == true) continue;
            page.changeSeats(seat1, seat2);
        }
        return true;
    },
    delRowSeats: function (row) {
        //删除指定行的座位
        var seats = jsonsql.query(`select * from json where (row != ${row}) order by row asc`, page.seats); //获得不等于指定行的座位
        if (!seats || seats.length == 0) return;         
        for (var index = row; index <= page.deskRow; index++) {
            var tempSeats = jsonsql.query(`select * from json where (row == ${index}) order by col asc`, seats);
            if (!tempSeats || tempSeats.length == 0) continue;
            $.each(tempSeats, function (index2, item) {
                item.row = item.row - 1; //行号减1
                item.changeSatus();
            });
        }
        page.deskRow = page.deskRow - 1;
        page.seats = seats;

    },
    delColSeats: function (col) {
        //删除指定列的座位
        var seats = jsonsql.query(`select * from json where (col != ${col}) order by row asc`, page.seats); //获得不等于指定行的座位
        if (!seats || seats.length == 0) return;
        $("SeatCol_" + col).remove(); //删除指定列的课桌
        for (var index = col; index <= page.deskCol; index++) {
            $("SeatCol_" + index).attr("id", index);
            var tempSeats = jsonsql.query(`select * from json where (col == ${index}) order by row asc`, seats);
            if (!tempSeats || tempSeats.length == 0) continue;
            $.each(tempSeats, function (index2, item) {
                item.col = item.col - 1; //行号减1
                item.changeSatus();
            });
        }
        page.deskCol = page.deskCol - 1;
        page.seats = seats;
    },
    revokeSeatToStudent: function (row, col) {
        //给已安排的座位撤销学生的座位安排：学生回到学生列表
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var seats = jsonsql.query(`select * from json where (col == ${col} && row ==${row} ) order by row asc`, page.seats);
        if (!seats || seats.length == 0) return;
        var seat = seats[0];
        if (seat.student instanceof Student) {
            $("#STU_" + seat.student.id).removeClass("student-hide");
        }
        seat.clearStudent(); //清空座位信息 
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        var tplInst = laytpl(seatTpl);
        tplInst.render(seat, function (html) {
            $("SEAT_R_" + seat.row + "_C_" + seat.col).replaceWith(html);// 渲染并输出结果  
        });
    },
    revokeRowSeats: function (row) {
        //撤销指定行的座位安排
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var seats = jsonsql.query(`select * from json where (row == ${row}) order by col asc`, page.seats);
        if (!seats || seats.length == 0) return;
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        var tplInst = laytpl(seatTpl);
        $.each(seats, function (index, item) {
            if (item.student instanceof Student) {
                $("#STU_" + seat.student.id).removeClass("student-hide");
            }
            item.clearStudent(); //清空座位信息
            tplInst.render(item, function (html) {
                $("SEAT_R_" + item.row + "_C_" + item.col).replaceWith(html);// 渲染并输出结果  
            });
        });
    },
    revokeColSeats: function (col) {
        //撤销指定列的座位安排,座位表上的学生返回到学生列表
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var seats = jsonsql.query(`select * from json where (col == ${col}) order by row asc`, page.seats);
        if (!seats || seats.length == 0) return;
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        var tplInst = laytpl(seatTpl);
        $.each(seats, function (index, item) {
            if (item.student instanceof Student) {
                $("#STU_" + seat.student.id).removeClass("student-hide");
            }
            item.clearStudent(); //清空座位信息
            tplInst.render(item, function (html) {
                $("SEAT_R_" + item.row + "_C_" + item.col).replaceWith(html);// 渲染并输出结果  
            });
        });
    },
    lockingSeat: function (row, col) {
        //锁定指定的座位,锁定后，不能进行人员安排
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        $("SEAT_R_" + row + "_C_" + col).addClass("seat-locked");
        var seats = jsonsql.query(`select * from json where (col == ${col} && row ==${row} ) order by row asc`, page.seats);
        if (seats && seats.length > 0) {
            seats[0].setLockedStatus(true);
            page.resetSeat(seats[0]); //重置座位
        }
    },
    unlockingSeat: function (row, col) {
        //解锁指定的座位,可进行人员安排
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        $("SEAT_R_" + row + "_C_" + col).removeClass("seat-locked");
        var seats = jsonsql.query(`select * from json where (col == ${col} && row ==${row} ) order by row asc`, page.seats);
        if (seats && seats.length > 0) {
            seats[0].setLockedStatus(false);
            page.resetSeat(seats[0]); //重置座位
        }
    },
    revokeLockedSeats: function () {
        //撤销所有锁定的座位，如果已分配人员，人员不进行清空
        var $ = layui.jquery;
        $.each(page.seats, function (index, item) {
            if (item.locked == true) {
                $("SEAT_R_" + item.row + "_C_" + item.col).removeClass("seat-locked");
                item.setLockedStatus(false); //解锁座位信息
            }
        });
    },
    clearSeatsByLockedStatus: function (lockedStatus) {
        //清空所有锁定的座位，如果已分配人员，进行清空，并加回学生列表
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        if (!lockedStatus) lockedStatus = false;
        var seatTpl = document.getElementById('seat-tpl').innerHTML; // 获取模板字符
        var tplInst = laytpl(seatTpl);
        $.each(page.seats, function (index, item) {
            if (item.locked == lockedStatus && item.allocationed == true) {
                var student = item.student;
                $("#STU_" + item.student.id).removeClass("student-hide");
                item.clearStudent; //清空学生座位信息
                tplInst.render(item, function (html) {
                    $("SEAT_R_" + item.row + "_C_" + item.col).replaceWith(html);// 渲染并输出结果  
                });
            }
        });
    },
    //从远程获得学生数据
    getStudents: function () {
        //学生数组
        const students = [
            new Student(1, "张晒晒", "男", 172),
            new Student(2, "刘东东", "女", 165),
            new Student(3, "李杰", "女", 165),
            new Student(4, "张三4", "男", 165),
            new Student(5, "张三5", "男", 165),
            new Student(6, "张三6", "女", 165),
            new Student(7, "张三7", "男", 165),
            new Student(8, "张三8", "女", 165),
            new Student(9, "张三9", "男", 165),
            new Student(10, "张三10", "男", 165),
            new Student(11, "张三11", "女", 165)
        ];
        page.students = students;
        page.studentListRender(); //进行数据渲染    
    },
    //学生列表渲染器
    studentListRender: function () {
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        var studentTpl = document.getElementById('student-tpl').innerHTML; // 获取模板字符
        $("#studentContainer").empty();//清空学生列表
        var tplInst = laytpl(studentTpl);
        $.each(page.students, function (index, item) {
            tplInst.render(item, function (html) {
                $("#studentContainer").append(html);// 渲染并输出结果  
            });
        });
    },
    clearStudentList: function () {
        $.each(page.seats, function (index, item) {
            item.clearSeat();
        });
        page.students = [];
        page.studentListRender();
        page.seatChartRender();
    },
    //设置座位表（初始始）
    setSeatChart: function () {
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        if (!page.deskRow) page.deskRow = 8;
        if (!page.deskCol) page.deskCol = 8;
        page.seats = [];
        for (var colIndex = 1; colIndex <= page.deskCol; colIndex++) {
            for (var rowIndex = 1; rowIndex <= page.deskRow; rowIndex++) {
                var item = new SeatInfo(rowIndex, colIndex);
                page.seats.push(item);
            }
        }
        page.seatChartRender();
    },
    //座位表渲染
    seatChartRender: function () {
        var $ = layui.jquery;
        var laytpl = layui.laytpl;
        $("#seat-container").empty();
        var colTpl = document.getElementById('seat-col-tpl').innerHTML; // 获取模板字符
        var tplInst = laytpl(colTpl);
        for (var colIndex = 1; colIndex <= page.deskCol; colIndex++) {
            var queryData = jsonsql.query("select * from json where (col == " + colIndex + ") order by row asc", page.seats);
            tplInst.render({ col: colIndex, items: queryData }, function (html) {
                $("#seat-container").append(html);// 渲染并输出结果  
            });
        }
    },
    //一键清空
    clearSeatChart: function () {
        var $ = layui.jquery;
        $.each(page.seats, function (index, item) {
            item.clearSeat();
        });
        $("#studentContainer .student").removeClass("student-hide");
        page.seatChartRender();
    }
};

//学生对象定义
function Student(id, name, sex, height) {
    this.id = id;
    this.name = name;
    this.sex = sex;
    this.height = height;
    this.row = 0;
    this.col = 0;
    this.setSeat = function (deskRow, deskCol) {
        this.row = deskRow;
        this.col = deskCol;
    };
    this.clearSeat = function () {
        this.row = 0;
        this.col = 0;
    }
};

//座位信息定义
function SeatInfo(deskRow, deskCol) {
    this.col = deskCol;  //课桌位于那列
    this.row = deskRow; //课桌位于那行
    this.locked = false; //是否被锁定
    this.allocationed = false; //已分配
    this.student = null;//学生信息：当没有分配时，为null,分别为学生对象
    //设置锁定状态
    this.setLockedStatus = function (locked) {
        this.locked = locked;
    };
    //设置学生信息
    this.setStudent = function (student) {
        if (this.student && this.student instanceof Student) {
            this.student.clearSeat(); //清空学生座位信息
        }
        if (student == undefined || student == null || !(student instanceof Student)) {
            this.allocationed = false; //未分配
            this.student = null;
        } else {
            this.allocationed = true; //已分配
            this.student = student;
            this.student.setSeat(this.row, this.col);
        }
    };
    //清空学生信息
    this.clearStudent = function () {
        if (this.student != undefined && this.student != null && this.student instanceof Student) {
            this.student.clearSeat(); //清空学生座位信息
        }
        this.allocationed = false; //未分配
        this.student = null;
    };
    //改变座位状态信息
    this.changeSatus = function () {
        if (this.student != undefined && this.student != null && this.student instanceof Student) {
            this.allocationed = true; //已分配
            this.student.setSeat(this.row, this.col);
        } else {
            this.allocationed = false; //未分配
        }
    };

};
